/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
export function csFkeep(a, callback, other) {
  // a arrays
  var avalues = a._values;
  var aindex = a._index;
  var aptr = a._ptr;
  var asize = a._size; // columns

  var n = asize[1]; // nonzero items

  var nz = 0; // loop columns

  for (var j = 0; j < n; j++) {
    // get current location of col j
    var p = aptr[j]; // record new location of col j

    aptr[j] = nz;

    for (; p < aptr[j + 1]; p++) {
      // check we need to keep this item
      if (callback(aindex[p], j, avalues ? avalues[p] : 1, other)) {
        // keep A(i,j)
        aindex[nz] = aindex[p]; // check we need to process values (pattern only)

        if (avalues) {
          avalues[nz] = avalues[p];
        } // increment nonzero items


        nz++;
      }
    }
  } // finalize A


  aptr[n] = nz; // trim arrays

  aindex.splice(nz, aindex.length - nz); // check we need to process values (pattern only)

  if (avalues) {
    avalues.splice(nz, avalues.length - nz);
  } // return number of nonzero items


  return nz;
}